
'use strict';

/**
	Part of Zombie Navigator
	Copyright © 2015  Zombie Navigator Developers
	
	@file
	@module
	@license AGPL-3.0+
*/


/* Used modules */
const _modMeta = require('../platform/meta');
const _modEnv = require('../platform/env');
const _modUri = require('../platform/uri');


/**
	Blacklisted systems (in lower case: winnt, darwin, ...) on which script
	autostart is disabled
	@type {Array}
	@private
*/
const _systemBlacklist = require('../system-blacklist.json');

/**
	@private
*/
const _demoPaths = require('../demo-paths.json');

/**
	List of preference names (see package.json)
	@private
*/
const {
	PREF_NAME_IGNORE_ENV_SCRIPT
} = require('../pref-names.json');

/**
	Help related preferences
	@private
*/
const _preferences = require('../platform/preferences').openPreferences(
	// readonly preferences
	[PREF_NAME_IGNORE_ENV_SCRIPT]
	,
	[]
);


/**
	@private
*/
const _checkPlatform = () => {
	const modMeta = _modMeta;
	
	if (-1 !== _systemBlacklist.indexOf(modMeta.getSystemName())) {
		// Disabled system
		const systemName = modMeta.getSystemDescription();
		throw new Error(systemName + ' support is disabled');
	}
	
	return true;
};


/**
	Environments variables to look for
	@private
*/
const ENV_NAME_SCRIPT_PATH = 'SCRIPT_PATH';
const ENV_NAME_DEMO = 'DEMO';


const _demoPrefix = 'scripts/demo/';
const _defaultDemo = 'main';

/**
	Get the URI of demo script
	@private
*/
const getDemoURI = function (demo) {
	const modMeta = _modMeta;
	
	const demos = _demoPaths;
	
	let demoPath = (demo in demos) ? demos[demo] : demos[_defaultDemo];
	
	return modMeta.getURIFromDataPath(_demoPrefix + demoPath);
};


/**
	Get the URI from a path
	XXX: Only absolute path is supported
	@private
*/
const pathToURI = function (path) {
	const modUri = _modUri;
	
	try {
		return modUri.filenameToURI(path);
	} catch (e) {
		throw new Error('Invalid path (maybe not absolute?)');
	}
};


/**
	Get the URI of the Zombie script to run
	@public
*/
const getScriptURI = function () {
	/*
		Check if this platform is enabled
	*/
	_checkPlatform();
	
	
	/*
		Look for environments
	*/
	const modEnv = _modEnv;
	const preferences = _preferences;
	
	if (!preferences[PREF_NAME_IGNORE_ENV_SCRIPT]) {
		if (modEnv.has(ENV_NAME_SCRIPT_PATH)) {
			const scriptPath = modEnv.get(ENV_NAME_SCRIPT_PATH);
			
			if ('' != scriptPath) {
				return pathToURI(scriptPath);
			}
		}
		
		if (modEnv.has(ENV_NAME_DEMO)) {
			const demoName = modEnv.get(ENV_NAME_DEMO);
			
			if ('' != demoName) {
				return getDemoURI(demoName);
			}
		}
	}
	
	return false;
};


/* Exports */
exports.getScriptURI = getScriptURI;


// vim: ts=4 noet ai

